package com.study.web.controller.user;

import cn.dev33.satoken.annotation.SaCheckLogin;
import com.study.app.domain.bo.AppUserEmergencyBo;
import com.study.app.domain.vo.AppUserEmergencyVo;
import com.study.app.service.IAppUserEmergencyService;
import com.study.common.core.controller.AppBaseController;
import com.study.common.core.domain.R;
import com.study.common.utils.AesGcmUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * App用户紧急联系人
 *
 * @author study
 * @date 2023-04-19
 */
@Slf4j
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/emergency")
public class AppUserEmergencyController extends AppBaseController {


    private final IAppUserEmergencyService iAppUserEmergencyService;


    /**
     * 获取当前用户紧急联系人信息
     *
     * @return
     */
    @SaCheckLogin
    @GetMapping("/userEmergency")
    public R<List<AppUserEmergencyVo>> getUserEmergencyContact() {
        return R.ok(iAppUserEmergencyService.queryListById(getUserId()));
    }

    /**
     * 新增/修改紧急联系人信息
     *
     * @return
     */
    @SaCheckLogin
    @PostMapping("/newModifyUrgent")
    public R<?> userNewModifyUrgent(@RequestBody AppUserEmergencyBo bo) {
        Boolean aBoolean = false;
        bo.setUserId(getUserId());
        bo.setName(AesGcmUtils.encrypt(bo.getName()));
        bo.setPhone(AesGcmUtils.encrypt(bo.getPhone()));
        if (bo.getId() != null) {
            aBoolean = iAppUserEmergencyService.updateByBo(bo);
            return R.ok(aBoolean);
        }
        if (!iAppUserEmergencyService.userJudge(getUserId())) {

            aBoolean = iAppUserEmergencyService.insertByBo(bo);
            return R.ok(aBoolean);
        }
        throw new RuntimeException("联系人添加已经达到上限");
    }

    /**
     * 用户删除紧急联系人
     *
     * @param id
     * @return
     */
    @SaCheckLogin
    @GetMapping("/delect")
    public R<?> userDelect(@Valid Long id) {
        return R.ok(iAppUserEmergencyService.deleteUser(id));
    }
}
